package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public ResponseResult search(UserSearchDto dto) {
        try {
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        CompletionSuggestionBuilder suggestion =
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(dto.getSearchWords()).skipDuplicates(true).size(10);
        SuggestBuilder keyWordSuggest = suggestBuilder.addSuggestion("keyWordSuggest", suggestion);
        searchRequest.source().suggest(keyWordSuggest);

            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            CompletionSuggestion KeySuggest = response.getSuggest().getSuggestion("keyWordSuggest");
            List<CompletionSuggestion.Entry.Option> options = KeySuggest.getOptions();
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().toString());
            }
            return ResponseResult.okResult(list);

        } catch (IOException e) {
            e.printStackTrace();
            //结果解析
            return null;
        }
    }
}
